package com.qk.common.util;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectRequest;
import com.qk.common.config.AliyunOSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class AliYunOSSOperators {

    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;

    public String upload(byte[] content, String objectName) throws Exception {
        // 创建OSSClient实例
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = null;
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(aliyunOSSProperties.getEndpoint())
                    .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(aliyunOSSProperties.getRegion())
                    .build();
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunOSSProperties.getBucketName(), objectName, new ByteArrayInputStream(content));
            // 上传文件
            ossClient.putObject(putObjectRequest);

            // 返回文件访问URL
            return "https://" + aliyunOSSProperties.getBucketName() + "." + aliyunOSSProperties.getEndpoint().substring(8) + "/" + objectName;
        } catch (Exception e) {
            log.error("Caught an OSSException: " + e.getMessage());
            throw e;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public void deleteExcept(List<String> excludeImageList) {
        OSS ossClient = null;
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(aliyunOSSProperties.getEndpoint())
                    .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                    .region(aliyunOSSProperties.getRegion())
                    .build();

            List<String> excludeImageKeys = excludeImageList.stream()
                    .filter(image -> image != null && !image.isEmpty())
                    .map(this::extractImageKey)
                    .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

            String nextMarker = null;
            int deletedCount = 0;
            do {
                com.aliyun.oss.model.ListObjectsRequest listObjectsRequest =
                        new com.aliyun.oss.model.ListObjectsRequest(aliyunOSSProperties.getBucketName());
                listObjectsRequest.setMarker(nextMarker);
                listObjectsRequest.setMaxKeys(1000);

                ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
                List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();

                List<String> imagesToDelete = objectSummaries.stream()
                        .map(OSSObjectSummary::getKey)
                        .filter(objectKey -> !excludeImageKeys.contains(objectKey))
                        .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
                for (String image : imagesToDelete) {
                    ossClient.deleteObject(aliyunOSSProperties.getBucketName(), image);
                    log.info("删除OSS中多余图片: {}", image);
                    deletedCount++;
                }

                nextMarker = objectListing.getNextMarker();
            } while (nextMarker != null);

            log.info("OSS图片清理完成，排除 {} 个有效图片，删除 {} 个无效图片", excludeImageKeys.size(), deletedCount);

        } catch (Exception e) {
            log.error("清理OSS图片时发生错误: " + e.getMessage(), e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    private String extractImageKey(String imageUrl) {
        if (imageUrl == null || imageUrl.isEmpty()) {
            return "";
        }

        int lastSlashIndex = imageUrl.lastIndexOf('/');
        if (lastSlashIndex >= 0 && lastSlashIndex < imageUrl.length() - 1) {
            return imageUrl.substring(lastSlashIndex + 1);
        }
        return imageUrl;
    }
}